package com.shiro.config;


import com.shiro.realm.UserRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration//用来做一些不好在yml配置文件里的配置,再交给IOC管理
public class ShiroConfig {
    @Bean
    public ShiroFilterFactoryBean shirFilter(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        //权限设置, 通过将访问的各个请求,所需的权限,以k-v的形式存在map集合里,再放入过滤器中
        Map<String, String> filterChainDefinitionMap = new HashMap<>();
        filterChainDefinitionMap.put("/main", "anon");
        filterChainDefinitionMap.put("/manage", "perms[manage]");
        filterChainDefinitionMap.put("/administrator", "roles[admin]");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        //设置登陆页面
        shiroFilterFactoryBean.setLoginUrl("/login");
        //设置未授权页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");
        return shiroFilterFactoryBean;
    }

    @Bean
    //Manager是shiro的核心部分, 负责安全认证和授权,而具体的方法步骤由传入的realm决定
    public DefaultWebSecurityManager securityManager(@Qualifier("getUserRealm") UserRealm userRealm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(userRealm);
        return defaultWebSecurityManager;
    }

    @Bean
    //创建一个UserRealm放到IOC里
    //默认将方法名做为Bean的name
    public UserRealm getUserRealm() {
        return new UserRealm();
    }
}
